package com.hbm.usercenter.http;

import com.hbm.usercenter.utils.LogUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by BS on 2017/6/5.
 */

public class NetClient {
    private static NetClient mNetClient;
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    private Request mRequest;

    private NetClient() {
        mClient = initOkHttpClient();
    }

    public final OkHttpClient mClient;

    private OkHttpClient initOkHttpClient() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .readTimeout(10000, TimeUnit.MILLISECONDS)//设置读取超时为10秒
                .connectTimeout(10000, TimeUnit.MILLISECONDS)//设置链接超时为10秒
                .build();
        return okHttpClient;
    }

    public static NetClient getNetClient() {
        if (mNetClient == null) {
            mNetClient = new NetClient();
        }
        return mNetClient;
    }

    public  String callNetSync(String url) throws IOException {
        return  callNetSync(url, null);
    }

    public String callNetSync(String url, Map<String, String> params) throws IOException {
        //有参数传入
        if (params != null && params.size() > 0) {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> info : params.entrySet()) {
                String key = info.getKey();
                String value = info.getValue();
                builder.add(key, value);
            }
            RequestBody body = builder.build();
            //            RequestBody formBody = new FormBody.Builder()
            //                    .add("username", "test")
            //                    .add("pwd","123456")
            //                    .build();
            mRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            LogUtils.d("POST-----"+mRequest.toString());

        } else {
            mRequest = new Request.Builder().url(url).build();
            LogUtils.d( "GET-----"+mRequest.toString());
        }

        Response response = getNetClient().initOkHttpClient().newCall(mRequest).execute();
        String json = response.body().string();
        return  json;
    }

    public void callNet(String url, final MyCallBack mCallback) {
        callNet(url, mCallback, null);
    }

    public void callNet(String url, final MyCallBack mCallback, Map<String, String> params) {

        //有参数传入
        if (params != null && params.size() > 0) {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> info : params.entrySet()) {
                String key = info.getKey();
                String value = info.getValue();
                builder.add(key, value);
            }
            RequestBody body = builder.build();
            //            RequestBody formBody = new FormBody.Builder()
            //                    .add("username", "test")
            //                    .add("pwd","123456")
            //                    .build();
            mRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            LogUtils.d("POST-----"+mRequest.toString());

        } else {
            mRequest = new Request.Builder().url(url).build();
            LogUtils.d( "GET-----"+mRequest.toString());
        }
        Call call = getNetClient().initOkHttpClient().newCall(mRequest);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mCallback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求网络成功说明服务器有响应，但返回的是什么我们无法确定，可以根据响应码判断
                if (response.code() == 200) {
                    //如果是200说明正常，调用MyCallBack的成功方法，传入数据
                    mCallback.onResponse(response.body().string());
                } else {
                    //如果不是200说明异常，调用MyCallBack的失败方法将响应码传入
                    //                    mCallback.onFailure(response.code());
                    LogUtils.d("connecting false");
                }
            }
        });
    }


}
